home *** CD-ROM | disk | FTP | other *** search
/ The 640 MEG Shareware Studio 2 / The 640 Meg Shareware Studio CD-ROM Volume II (Data Express)(1993).ISO / clang / zcpp_jae.zip / CPP1.C < prev    next >
Text File  |  1992-07-14  |  28KB  |  822 lines

  1. /*
  2.  
  3.  
  4.  Copyright (C) 1990 Texas Instruments Incorporated.
  5.  
  6.  Permission is granted to any individual or institution to use, copy, modify,
  7.  and distribute this software, provided that this complete copyright and
  8.  permission notice is maintained, intact, in all copies and supporting
  9.  documentation.
  10.  
  11.  Texas Instruments Incorporated provides this software "as is" without
  12.  express or implied warranty.
  13.  
  14.  
  15.  * CPP main program.
  16.  *
  17.  * Edit history
  18.  * 21-May-84    MM    "Field test" release
  19.  * 23-May-84    MM    Some minor hacks.
  20.  * 30-May-84    ARF    Didn't get enough memory for __DATE__
  21.  *            Added code to read stdin if no input
  22.  *            files are provided.
  23.  * 29-Jun-84    MM    Added ARF's suggestions, Unixifying cpp.
  24.  * 11-Jul-84    MM    "Official" first release (that's what I thought!)
  25.  * 22-Jul-84    MM/ARF/SCK Fixed line number bugs, added cpp recognition
  26.  *            of #line, fixed problems with #include.
  27.  * 23-Jul-84    MM    More (minor) include hacking, some documentation.
  28.  *            Also, redid cpp's #include files
  29.  * 25-Jul-84    MM    #line filename isn't used for #include searchlist
  30.  *            #line format is <number> <optional name>
  31.  * 25-Jul-84    ARF/MM    Various bugs, mostly serious.  Removed homemade doprint
  32.  * 01-Aug-84    MM    Fixed recursion bug, remove extra newlines and
  33.  *            leading whitespace from cpp output.
  34.  * 02-Aug-84    MM    Hacked (i.e. optimized) out blank lines and unneeded
  35.  *            whitespace in general.  Cleaned up unget()'s.
  36.  * 03-Aug-84    Keie    Several bug fixes from Ed Keizer, Vrije Universitet.
  37.  *            -- corrected arg. count in -D and pre-defined
  38.  *            macros.  Also, allow \n inside macro actual parameter
  39.  *            lists.
  40.  * 06-Aug-84    MM    If debugging, dump the preset vector at startup.
  41.  * 12-Aug-84    MM/SCK    Some small changes from Sam Kendall
  42.  * 15-Aug-84    Keie/MM    cerror, cwarn, etc. take a single string arg.
  43.  *            cierror, etc. take a single int. arg.
  44.  *            changed LINE_PREFIX slightly so it can be
  45.  *            changed in the makefile.
  46.  * 31-Aug-84    MM    USENET net.sources release.
  47.  *  7-Sep-84    SCH/ado Lint complaints
  48.  * 10-Sep-84    Keie    Char's can't be signed in some implementations
  49.  * 11-Sep-84    ado    Added -C flag, pathological line number fix
  50.  * 13-Sep-84    ado    Added -E flag (does nothing) and "-" file for stdin.
  51.  * 14-Sep-84    MM    Allow # 123 as a synonym for #line 123
  52.  * 19-Sep-84    MM    scanid always reads to token, make sure #line is
  53.  *            written to a new line, even if -C switch given.
  54.  *            Also, cpp - - reads stdin, writes stdout.
  55.  * 03-Oct-84    ado/MM    Several changes to line counting and keepcomments
  56.  *            stuff.  Also a rewritten control() hasher -- much
  57.  *            simpler and no less "perfect". Note also changes
  58.  *            in cpp3.c to fix numeric scanning.
  59.  * 04-Oct-84    MM    Added recognition of macro formal parameters if
  60.  *            they are the only thing in a string, per the
  61.  *            draft standard.
  62.  * 08-Oct-84    MM    One more attack on scannumber
  63.  * 15-Oct-84    MM/ado    Added -N to disable predefined symbols.  Fixed
  64.  *            linecount if COMMENT_INVISIBLE enabled.
  65.  * 22-Oct-84    MM    Don't evaluate the #if/#ifdef argument if
  66.  *            compilation is supressed.  This prevents
  67.  *            unnecessary error messages in sequences such as
  68.  *                #ifdef FOO        -- undefined
  69.  *                #if FOO == 10    -- shouldn't print warning
  70.  * 25-Oct-84    MM    Fixed bug in false ifdef supression.  On vms,
  71.  *            #include <foo> should open foo.h -- this duplicates
  72.  *            the behavior of Vax-C
  73.  * 31-Oct-84    ado/MM    Parametized $ in indentifiers.  Added a better
  74.  *            token concatenator and took out the trial
  75.  *            concatenation code.  Also improved #ifdef code
  76.  *            and cleaned up the macro recursion tester.
  77.  *  2-Nov-84    MM/ado    Some bug fixes in token concatenation, also
  78.  *            a variety of minor (uninteresting) hacks.
  79.  *  6-Nov-84    MM    Happy Birthday.  Broke into 4 files and added
  80.  *            #if sizeof (basic_types)
  81.  *  9-Nov-84    MM    Added -S* for pointer type sizes
  82.  * 13-Nov-84    MM    Split cpp1.c, added vms defaulting
  83.  * 23-Nov-84    MM/ado    -E supresses error exit, added CPP_INCLUDE,
  84.  *            fixed strncpy bug.
  85.  *  3-Dec-84    ado/MM    Added OLD_PREPROCESSOR
  86.  *  7-Dec-84    MM    Stuff in Nov 12 Draft Standard
  87.  * 17-Dec-84    george    Fixed problems with recursive macros
  88.  * 17-Dec-84    MM    Yet another attack on #if's (f/t)level removed.
  89.  * 07-Jan-85    ado    Init defines before doing command line options
  90.  *            so -Uunix works.
  91.  * 21-Oct-85    RMS    Rename `token' to `tokenbuf'.
  92.  *            Allocate it dynamically, with size in `tokenbsize'.
  93.  * 23-Oct-85    RMS    Do not print message about number of errors.
  94.  *
  95.  * 19-Jan-90    DKM     Support for MVS.
  96.  * 04-May-90    MJF     Added predefined constant for target_arch.
  97.  * 18-May-90    MBN     Conditional compilation on COOL to get "clean" cpp
  98.  * 21-May-90    MJF     Added DECLARE_ONCE for CCC -X
  99.  */
  100.  
  101. /*)BUILD
  102.     $(PROGRAM)    = cpp
  103.     $(FILES)    = { cpp1 cpp2 cpp3 cpp4 cpp5 cpp6 }
  104.     $(INCLUDE)    = { cppdef.h cpp.h }
  105.     $(STACK)    = 2000
  106.     $(TKBOPTIONS)    = {
  107.         STACK    = 2000
  108.     }
  109. */
  110.  
  111. /*    DOCUMENTATION
  112.  
  113. title    cpp        C Pre-Processor
  114. index            C pre-processor
  115.  
  116. synopsis
  117.     cpp [-options] [infile [outfile]]
  118.  
  119. description
  120.  
  121.     CPP reads a C source file, expands macros and include
  122.     files, and writes an input file for the C compiler.
  123.     If no file arguments are given, CPP reads from stdin
  124.     and writes to stdout.  If one file argument is given,
  125.     it will define the input file, while two file arguments
  126.     define both input and output files.  The file name "-"
  127.     is a synonym for stdin or stdout as appropriate.
  128.  
  129.     The following options are supported.  Options may
  130.     be given in either case.
  131.  
  132.     -C        If set, source-file comments are written
  133.     to the output file.  This allows the output of CPP to be
  134.     used as the input to a program, such as lint, that expects
  135.     commands embedded in specially-formatted comments.
  136.  
  137.     -Dname=value    Define the name as if the programmer wrote
  138.  
  139.         #define name value
  140.  
  141.     at the start of the first file.  If "=value" is not
  142.     given, a value of "1" will be used.
  143.  
  144.     On non-unix systems, all alphabetic text will be forced
  145.     to upper-case.
  146.  
  147.     -E        Always return "success" to the operating
  148.     system, even if errors were detected.  Note that some fatal
  149.     errors, such as a missing #include file, will terminate
  150.     CPP, returning "failure" even if the -E option is given.
  151.  
  152.     -Idirectory    Add this directory to the list of
  153.     directories searched for #include "..." and #include <...>
  154.     commands.  Note that there is no space between the
  155.     "-I" and the directory string.  More than one -I command
  156.     is permitted.  On non-Unix systems "directory" is forced
  157.     to upper-case.
  158.  
  159.     -N        CPP normally predefines some symbols defining
  160.     the target computer and operating system.  If -N is specified,
  161.     no symbols will be predefined.  If -N -N is specified, the
  162.     "always present" symbols, __LINE__, __FILE__, and __DATE__
  163.     are not defined.
  164.  
  165.     -Stext        CPP normally assumes that the size of
  166.     the target computer's basic variable types is the same as the size
  167.     of these types of the host computer.  (This can be overridden
  168.     when CPP is compiled, however.)  The -S option allows dynamic
  169.     respecification of these values.  "text" is a string of
  170.     numbers, separated by commas, that specifies correct sizes.
  171.     The sizes must be specified in the exact order:
  172.  
  173.         char short int long float double
  174.  
  175.     If you specify the option as "-S*text", pointers to these
  176.     types will be specified.  -S* takes one additional argument
  177.     for pointer to function (e.g. int (*)())
  178.  
  179.     For example, to specify sizes appropriate for a PDP-11,
  180.     you would write:
  181.  
  182.            c s i l f d func
  183.          -S1,2,2,2,4,8,
  184.         -S*2,2,2,2,2,2,2
  185.  
  186.     Note that all values must be specified.
  187.  
  188.     -Uname        Undefine the name as if
  189.  
  190.         #undef name
  191.  
  192.     were given.  On non-Unix systems, "name" will be forced to
  193.     upper-case.
  194.  
  195.     -Xnumber    Enable debugging code.  If no value is
  196.                     given, a value of 1 will be used.
  197.         -X1             debug print of files #included
  198.         -X2             debug inserts #control as comments in output
  199.         -X3             debug does both -X1 and -X2
  200.  
  201. Pre-Defined Variables
  202.  
  203.     When CPP begins processing, the following variables will
  204.     have been defined (unless the -N option is specified):
  205.  
  206.     Target computer (as appropriate):
  207.  
  208.         pdp11, vax, M68000 m68000 m68k
  209.  
  210.     Target operating system (as appropriate):
  211.  
  212.         rsx, rt11, vms, unix
  213.  
  214.     Target compiler (as appropriate):
  215.  
  216.         decus, vax11c
  217.  
  218.     The implementor may add definitions to this list.
  219.     The default definitions match the definition of the
  220.     host computer, operating system, and C compiler.
  221.  
  222.     The following are always available unless undefined (or
  223.     -N was specified twice):
  224.  
  225.     __FILE__    The input (or #include) file being compiled
  226.     (as a quoted string).
  227.  
  228.     __LINE__    The line number being compiled.
  229.  
  230.     __DATE__    The date of compilation as "Mmm dd yy"
  231.  
  232.     __TIME__    The time of compilation as "hh:mm:ss"
  233.  
  234.     __STDC__    The constant 1.
  235.  
  236.     Thus,
  237.         printf("Bug at line %s,", __LINE__);
  238.         printf(" source file %s", __FILE__);
  239.         printf(" compiled on %s", __DATE__);
  240.  
  241. Draft Proposed Ansi Standard Considerations
  242.  
  243.     When CPP is itself compiled, many features of the Draft
  244.     Proposed Standard that are incompatible with existing
  245.     preprocessors may be disabled.  See the comments in CPP's
  246.     source for details.
  247.  
  248.     Comments are removed from the input text.  The comment
  249.     is replaced by a single space character.  The -C option
  250.     preserves comments, writing them to the output file.
  251.  
  252.     The '$' character is considered to be a letter.  This is
  253.     a permitted extension.
  254.  
  255.     The following new features of C are processed by CPP:
  256.     #elif expression    (_#else _#if)
  257.     '\xNNN'             (Hexadecimal constant)
  258.     '\a'                (Ascii BELL)
  259.     '\v'                (Ascii Vertical Tab)
  260.     #if defined NAME    1 if defined, 0 if not
  261.     #if defined (NAME)  1 if defined, 0 if not  
  262.     #if sizeof (basic type)
  263.     unary +
  264.     U, 123LU            Unsigned ints and longs.
  265.     12.3L               Long double numbers
  266.     token_#token        Token concatenation
  267.     #include token      Expands to filename
  268.         #error tokens       Flags an error
  269.  
  270.     The Draft Proposed Standard has extended C, adding a constant
  271.     string concatenation operator, where
  272.  
  273.         "foo" "bar"
  274.  
  275.     is regarded as the single string "foobar".  (This does not
  276.     affect CPP's processing but does permit a limited form of
  277.     macro argument substitution into strings as will be discussed.)
  278.  
  279.     The Standard Committee plans to add token concatenation
  280.     to #define command lines as follows:
  281.     The sequence "Token1 ## Token2" is treated
  282.     as if the programmer wrote "Token1Token2".  This could
  283.     be used as follows:
  284.  
  285.         #line 123
  286.         #define ATLINE foo ## __LINE__
  287.  
  288.     ATLINE would be defined as foo123.
  289.  
  290.     If the tokens T1 and T2 are concatenated into T3,
  291.     this implementation operates as follows:
  292.  
  293.       1. Expand T1 if it is a macro.
  294.       2. Expand T2 if it is a macro.
  295.       3. Join the tokens, forming T3.
  296.       4. Expand T3 if it is a macro.
  297.  
  298.         If a macro parameter is immediately proceeded by a #, string
  299.         quotes (") are placed around the substituted parameter and
  300.         a \ character is inserted before each " or \ character that
  301.         appears surrounding,or inside a string literal or character
  302.         constant in the argument.
  303.  
  304.         Example:
  305.         #define vprint(name, size) \
  306.           printf(#name "[" "size" "] = {\n")
  307.           ... vprint(vector, 123);
  308.  
  309.     expands (effectively) to
  310.  
  311.           vprint("vector[123] = {\n");
  312.  
  313.     Note that this will be useful if your C compiler supports
  314.     the new string concatenation operation noted above.
  315.  
  316. EXTENSIONS
  317.  
  318.     An extended macro facility is provided which allows and arbitrary unix
  319.     process to act as a macro expander.  To define a macro do one of the
  320.     following:
  321.  
  322.     #pragma defmacro name <file> options
  323.     #pragma defmacro name "file" options
  324.     #pragma defmacro name program options
  325.  
  326.     This provides a mapping between macro names and the file to be
  327.     executed, which is on the include search path. "options" is zero or
  328.         more of the following: 
  329.     recursive    - when present, the macro may be recursively expanded.
  330.     expanding    - when present, input to the macro is macro-expanded.
  331.     delimiter=?  - the default delimiter of ; is replaced with ?
  332.     condition=?  - expand only if this char found after name
  333.     other        - unknown options are passed as arguments to the
  334.                macro expander.
  335.  
  336.     When a "defmacro" style macro's name is found, the name and everything
  337.     until the delimiter (includling all matching {} [] () <> "" '' and
  338.     comments found along the way) is piped into the macro procedure's
  339.     standard-input.  The procedure's standard output is scanned by CPP for
  340.     further processing. The expansion replaces the macro call.
  341.     number.
  342.  
  343. error messages
  344.  
  345.     Many.  CPP prints warning or error messages if you try to
  346.     use multiple-byte character constants (non-transportable)
  347.     if you #undef a symbol that was not defined, or if your
  348.     program has potentially nested comments.
  349.  
  350. authors
  351.  
  352.     Martin Minow (Origional version)
  353.         LaMott Oren  (Macro extensions and ANSI compatability)
  354.  
  355. bugs
  356.  
  357.     The #if expression processor uses signed integers only.
  358.     I.e, #if 0xFFFFu < 0 may be TRUE.
  359.  
  360.         This program differs from tha ANSI specification as follows:
  361.       Trigraph sequences aren't implemented.
  362.  
  363. */
  364.  
  365. #include    <stdio.h>
  366. #include    <ctype.h>
  367. #include    "cppdef.h"
  368. #include    "cpp.h"
  369.  
  370. #if HOST == SYS_MVS
  371. extern char *_stdiamp = "prompt=";  /* no prompting from sysin */
  372. extern char *_stdoamp = "print=no"; /* stdout doesn't need page fmt attr. */
  373. extern char *_stdeamp = "print=no"; /* stderr doesn't need page fmt attr. */
  374. #endif
  375.  
  376. #ifdef COOL
  377. /*
  378.  * Table of internal macros
  379.  *   (Alternating strings and function pointers, termnated with NULL)
  380.  */
  381. extern int parmtype();            /* Make names for parameterized types */
  382. extern int define_symbol();         /* Define a symbol in a package */
  383. extern int define_macro();        /* Define a fancy macro */
  384. extern int member();            /* Symbolic equality test */
  385. extern int class_macro();        /* C++ class processing */
  386. extern int classmac();            /* C++ class processing */
  387. extern int template();            /* Paramertized type definition */
  388. extern int declare();            /* Paramertized type declaration */
  389. extern int declare_once();        /* Paramertized type declaration */
  390. extern int implement();            /* Paramertized type code generation */
  391. extern int implement_n();        /* Paramertized type code generation */
  392. extern int exception();            /* Error recovery code generation */
  393. extern int generate();            /* macro looping mechanism */
  394. extern int compress();            /* compress out white space */
  395.  
  396. struct expander_pair internal_macros[] = {
  397.   {"parmtype", parmtype},
  398.   {"define_symbol", define_symbol},
  399.   {"macro", define_macro},
  400.   {"member", member},
  401.   {"class", class_macro},
  402.   {"classmac", classmac},
  403.   {"template", template},
  404.   {"declare", declare},
  405.   {"declare_once", declare_once},
  406.   {"implement", implement},
  407.   {"implement_n", implement_n},
  408.   {"exception", exception},
  409.   {"generate", generate},
  410.   {"compress", compress},
  411.   {NULL, NULL}};
  412.  
  413. #endif
  414.  
  415. /*
  416.  * Commonly used global variables:
  417.  * line        is the current input line number.
  418.  * wrongline    is set in many places when the actual output
  419.  *        line is out of sync with the numbering, e.g,
  420.  *        when expanding a macro with an embedded newline.
  421.  *
  422.  * tokenbuf    holds the last identifier scanned (which might
  423.  *        be a candidate for macro expansion).
  424.  * errors    is the running cpp error counter.
  425.  * infile    is the head of a linked list of input files (extended by
  426.  *        #include and macros being expanded).  infile always points
  427.  *        to the current file/macro.  infile->parent to the includer,
  428.  *        etc.  infile->fd is NULL if this input stream is a macro.
  429.  */
  430. int        line;            /* Current line number        */
  431. int        wrongline;        /* Force #line to compiler    */
  432. char        *tokenbuf;        /* Buffer for current input token */
  433. int        tokenbsize;        /* Allocated size of tokenbuf, */
  434.                     /* not counting zero at end.  */
  435. int        errors;            /* cpp error counter        */
  436. FILEINFO    *infile = NULL;        /* Current input file        */
  437. int        debug;            /* TRUE if debugging now    */
  438. /*
  439.  * This counter is incremented when a macro expansion is initiated.
  440.  * If it exceeds a built-in value, the expansion stops -- this tests
  441.  * for a runaway condition:
  442.  *    #define X Y
  443.  *    #define Y X
  444.  *    X
  445.  * This can be disabled by falsifying rec_recover.  (Nothing does this
  446.  * currently: it is a hook for an eventual invocation flag.)
  447.  */
  448. int        recursion;        /* Infinite recursion counter    */
  449. int        rec_recover = TRUE;    /* Unwind recursive macros    */
  450. DEFBUF            *macro;                /* Catches start of infinite macro */
  451.  
  452. /*
  453.  * instring is set TRUE when a string is scanned.  It modifies the
  454.  * behavior of the "get next character" routine, causing all characters
  455.  * to be passed to the caller (except <DEF_MAGIC>).  Note especially that
  456.  * comments and \<newline> are not removed from the source.  (This
  457.  * prevents cpp output lines from being arbitrarily long).
  458.  *
  459.  * inmacro is set by #define -- it absorbs comments and converts
  460.  * form-feed and vertical-tab to space, but returns \<newline>
  461.  * to the caller.  Strictly speaking, this is a bug as \<newline>
  462.  * shouldn't delimit tokens, but we'll worry about that some other
  463.  * time -- it is more important to prevent infinitly long output lines.
  464.  *
  465.  * instring and inmarcor are parameters to the get() routine which
  466.  * were made global for speed.
  467.  */
  468. int        instring = FALSE;    /* TRUE if scanning string    */
  469. int        inmacro = FALSE;    /* TRUE if #defining a macro    */
  470.  
  471. /*
  472.  * work[] and workp are used to store one piece of text in a temporay
  473.  * buffer.  To initialize storage, set workp = work.  To store one
  474.  * character, call save(c);  (This will fatally exit if there isn't
  475.  * room.)  To terminate the string, call save(EOS).  Note that
  476.  * the work buffer is used by several subroutines -- be sure your
  477.  * data won't be overwritten.  The extra byte in the allocation is
  478.  * needed for string formal replacement.
  479.  */
  480. char        work[NWORK + 1];    /* Work buffer            */
  481. char        *workp;            /* Work buffer pointer        */
  482.  
  483. /*
  484.  * keepcomments is set TRUE by the -C option.  If TRUE, comments
  485.  * are written directly to the output stream.  This is needed if
  486.  * the output from cpp is to be passed to lint (which uses commands
  487.  * embedded in comments).  cflag contains the permanent state of the
  488.  * -C flag.  keepcomments is always falsified when processing #control
  489.  * commands and when compilation is supressed by a false #if
  490.  *
  491.  * If eflag is set, CPP returns "success" even if non-fatal errors
  492.  * were detected.
  493.  *
  494.  * If nflag is non-zero, no symbols are predefined except __LINE__.
  495.  * __FILE__, and __DATE__.  If nflag > 1, absolutely no symbols
  496.  * are predefined.
  497.  */
  498. int        keepcomments = FALSE;    /* Write out comments flag    */
  499. int        cflag = FALSE;        /* -C option (keep comments)    */
  500. int        eflag = FALSE;        /* -E option (never fail)    */
  501. int        nflag = 0;        /* -N option (no predefines)    */
  502.  
  503. /*
  504.  * ifstack[] holds information about nested #if's.  It is always
  505.  * accessed via *ifptr.  The information is as follows:
  506.  *    WAS_COMPILING    state of compiling flag at outer level.
  507.  *    ELSE_SEEN    set TRUE when #else seen to prevent 2nd #else.
  508.  *    TRUE_SEEN    set TRUE when #if or #elif succeeds
  509.  * ifstack[0] holds the compiling flag.  It is TRUE if compilation
  510.  * is currently enabled.  Note that this must be initialized TRUE.
  511.  */
  512. char        ifstack[BLK_NEST] = { TRUE };    /* #if information    */
  513. char        *ifptr = ifstack;        /* -> current ifstack[] */
  514.  
  515. /*
  516.  * incdir[] stores the -i directories (and the system-specific
  517.  * #include <...> directories.
  518.  */
  519. char    *incdir[NINCLUDE];        /* -i directories        */
  520. char    **incend = incdir;        /* -> free space in incdir[]    */
  521.  
  522. /*
  523.  * This is the table used to predefine target machine and operating
  524.  * system designators.  It may need hacking for specific circumstances.
  525.  * Note: it is not clear that this is part of the Ansi Standard.
  526.  * The -N option supresses preset definitions.
  527.  */
  528. char    *preset[] = {            /* names defined at cpp start    */
  529. #ifdef    MACHINE
  530.     MACHINE,
  531. #endif
  532. #ifdef    SYSTEM
  533.     SYSTEM,
  534. #endif
  535. #ifdef    TARGET_ARCH
  536.     TARGET_ARCH,
  537. #endif
  538. #ifdef    COMPILER
  539.     COMPILER,
  540. #endif
  541. #ifdef  CH_SET
  542.          CH_SET,
  543. #endif
  544. #if    DEBUG
  545.     "decus_cpp",            /* Ourselves!            */
  546. #endif
  547.     NULL                /* Must be last            */
  548. };
  549.  
  550.  
  551. main(argc, argv)
  552. int        argc;
  553. char        *argv[];
  554. {
  555.     register int    i;
  556.  
  557. #if HOST == SYS_VMS
  558.     argc = getredirection(argc, argv);    /* vms >file and <file    */
  559. #endif
  560.     initdefines();                /* O.S. specific def's    */
  561.     i = dooptions(argc, argv);        /* Command line -flags    */
  562.     switch (i) {
  563.     case 3:
  564.         /*
  565.          * Get output file, "-" means use stdout.
  566.          */
  567.         if (!streq(argv[2], "-")) {
  568. #if HOST == SYS_VMS
  569.         /*
  570.          * On vms, reopen stdout with "vanilla rms" attributes.
  571.          */
  572.         if ((i = creat(argv[2], 0, "rat=cr", "rfm=var")) == -1
  573.          || dup2(i, fileno(stdout)) == -1) {
  574. #else
  575.         if (freopen(argv[2], "w", stdout) == NULL) {
  576. #endif
  577.             perror(argv[2]);
  578.             cerror("Can't open output file \"%s\"", argv[2]);
  579.             exit(IO_ERROR);
  580.         }
  581.         }                /* Continue by opening input    */
  582.     case 2:                /* One file -> stdin        */
  583.         /*
  584.          * Open input file, "-" means use stdin.
  585.          */
  586.         if (!streq(argv[1], "-")) {
  587.         if (freopen(argv[1], "r", stdin) == NULL) {
  588.             perror(argv[1]);
  589.             cerror("Can't open input file \"%s\"", argv[1]);
  590.             exit(IO_ERROR);
  591.         }
  592.         strcpy(work, argv[1]);    /* Remember input filename    */
  593.         break;
  594.         }                /* Else, just get stdin        */
  595.     case 0:                /* No args?            */
  596.     case 1:                /* No files, stdin -> stdout    */
  597. #if (HOST == SYS_UNIX  || HOST == SYS_OS2 || HOST == SYS_XENIX || HOST == SYS_MVS)
  598.         work[0] = EOS;        /* Unix can't find stdin name    */
  599. #else
  600.         fgetname(stdin, work);    /* Vax-11C, Decus C know name    */
  601. #endif
  602.         break;
  603.  
  604.     default:
  605.         exit(IO_ERROR);        /* Can't happen            */
  606.     }
  607.     setincdirs();            /* Setup -I include directories    */
  608.     addfile(stdin, work);        /* "open" main input file    */
  609. #if DEBUG
  610.     if (debug > 0)
  611.         dumpdef("preset #define symbols");
  612. #endif
  613.     cppmain();            /* Process main file        */
  614.     if ((i = (ifptr - &ifstack[0])) != 0) {
  615. #if OLD_PREPROCESSOR
  616.         ciwarn("Inside #ifdef block at end of input, depth = %d", i);
  617. #else
  618.         cierror("Inside #ifdef block at end of input, depth = %d", i);
  619. #endif
  620.     }
  621.     fclose(stdout);
  622.     if (errors > 0 && !eflag)
  623.       exit(IO_ERROR);
  624. #ifdef COOL
  625.     finish_symbols();
  626. #endif
  627.     exit(IO_NORMAL);        /* No errors or -E option set    */
  628. }
  629.  
  630. FILE_LOCAL
  631. cppmain()
  632. /*
  633.  * Main process for cpp -- copies tokens from the current input
  634.  * stream (main file, include file, or a macro) to the output
  635.  * file.
  636.  */
  637. {
  638.     register int        c;        /* Current character    */
  639.     register int        counter;    /* newlines and spaces    */
  640.     extern int        output();    /* Output one character    */
  641.  
  642.     /* Initialize for reading tokens */
  643.     tokenbsize = 50;
  644.     tokenbuf = getmem (tokenbsize + 1);
  645.  
  646.     /*
  647.      * Explicitly output a #line at the start of cpp output so
  648.      * that lint (etc.) knows the name of the original source
  649.      * file.  If we don't do this explicitly, we may get
  650.      * the name of the first #include file instead.
  651.      */
  652.     sharp();
  653.     /*
  654.      * This loop is started "from the top" at the beginning of each line
  655.      * wrongline is set TRUE in many places if it is necessary to write
  656.      * a #line record.  (But we don't write them when expanding macros.)
  657.      *
  658.      * The counter variable has two different uses:  at
  659.      * the start of a line, it counts the number of blank lines that
  660.      * have been skipped over.  These are then either output via
  661.      * #line records or by outputting explicit blank lines.
  662.       * When expanding tokens within a line, the counter remembers
  663.      * whether a blank/tab has been output.  These are dropped
  664.      * at the end of the line, and replaced by a single blank
  665.      * within lines.
  666.      */
  667.     for (;;) {
  668.         counter = 0;            /* Count empty lines    */
  669.         for (;;) {                /* For each line, ...    */
  670.           while (type[(c = get())] == SPA) /* Skip leading blanks    */
  671.         if (keepcomments)        /* in this line.    */
  672.           putchar(c);
  673.           if (c == '\n')            /* If line's all blank,    */
  674.         if(keepcomments)
  675.           putchar('\n');
  676.         else
  677.           ++counter;            /* Do nothing now    */
  678.           else if (c == '#') {        /* Is 1st non-space '#'    */
  679.         keepcomments = FALSE;        /* Don't pass comments    */
  680.         counter = control(counter);    /* Yes, do a #command    */
  681.         keepcomments = (cflag && compiling);
  682.           }
  683.           else if (c == EOF_CHAR)        /* At end of file?    */
  684.         break;
  685.           else if (!compiling) {        /* #ifdef false?    */
  686.         skipnl();            /* Skip to newline    */
  687.         if(keepcomments)
  688.           putchar('\n');
  689.         else
  690.           counter++;            /* Count it, too.    */
  691.           }
  692.           else {
  693.         break;                /* Actual token        */
  694.           }
  695.         }
  696.         if (c == EOF_CHAR)            /* Exit process at    */
  697.         break;                /* End of file        */
  698.         /*
  699.          * If the loop didn't terminate because of end of file, we
  700.          * know there is a token to compile.  First, clean up after
  701.          * absorbing newlines.  counter has the number we skipped.
  702.          */
  703.         if (wrongline && infile->fp != NULL)
  704.         sharp();            /* Output # line number    */
  705.         else {                /* If just a few, stuff    */
  706.         while (--counter >= 0)        /* them out ourselves    */
  707.             putchar('\n');
  708.         }
  709.         /*
  710.          * Process each token on this line.
  711.          */
  712.         unget();                /* Reread the char.    */
  713.         for (;;) {                /* For the whole line,    */
  714.           for (counter = 0; (type[(c = get())] == SPA);) {
  715.         if(keepcomments)
  716.           putchar(c);
  717.         else {
  718. #if COMMENT_INVISIBLE
  719.           if (c != COM_SEP)
  720.             counter++;
  721. #else
  722.           counter++;          /* Skip over blanks    */
  723. #endif
  724.         }
  725.           }
  726.           if (c == EOF_CHAR || c == '\n')
  727.         goto end_line;          /* Exit line loop    */
  728.           else if (counter > 0)      /* If we got any spaces    */
  729.         putchar(' ');          /* Output one space    */
  730.           c = macroid(c);          /* Grab the token    */
  731.           if (c == EOF_CHAR || c == '\n') /* From macro exp error    */
  732.         goto end_line;          /* Exit line loop    */
  733.           switch (type[c]) {
  734.           case LET:
  735.         fputs(tokenbuf, stdout);  /* Quite ordinary token    */
  736.         break;
  737.  
  738.  
  739.           case DIG:              /* Output a number    */
  740.           case DOT:              /* Dot may begin floats    */
  741.         scannumber(c, output);
  742.         break;
  743.  
  744.           case QUO:              /* char or string const    */
  745.         scanstring(c, output);      /* Copy it to output    */
  746.         break;
  747.  
  748.           default:              /* Some other character    */
  749.         cput(c);          /* Just output it    */
  750.         break;
  751.           }                  /* Switch ends        */
  752.         }                  /* Line for loop    */
  753. end_line:   if (c == '\n') {            /* Compiling at EOL?    */
  754.         putchar('\n');            /* Output newline, if    */
  755.         if (infile->fp == NULL)        /* Expanding a macro,    */
  756.             wrongline = TRUE;        /* Output # line later    */
  757.         }
  758.     }                    /* Continue until EOF    */
  759. }
  760.  
  761. output(c)
  762. int        c;
  763. /*
  764.  * Output one character to stdout -- output() is passed as an
  765.  * argument to scanstring()
  766.  */
  767. {
  768. #if COMMENT_INVISIBLE
  769.     if (c != TOK_SEP && c != COM_SEP)
  770. #else
  771.     if (c != TOK_SEP)
  772. #endif
  773.         putchar(c);
  774. }
  775.  
  776. FILE_LOCAL
  777. sharp()
  778. /*
  779.  * Output a line number line.
  780.  */
  781. {
  782.     register char        *name;
  783.  
  784.     if (keepcomments)            /* Make sure # comes on    */
  785.         putchar('\n');            /* a fresh, new line.    */
  786.     printf("#%s %d", LINE_PREFIX, line);
  787.     if (infile->fp != NULL) {
  788.         name = (infile->progname != NULL)
  789.         ? infile->progname : infile->filename;
  790.         printf(" \"%s\"", ESCNAME(name)); 
  791.     }
  792.     putchar('\n');
  793.     wrongline = FALSE;
  794. }
  795.  
  796.  
  797. #if defined(DOS) || defined(MSDOS)
  798.  
  799. /* escape all non-escaped backslashes in the pathname into a
  800. static buffer and return a pointer to the escaped pathname */
  801.  
  802. char*
  803. EscPathName(char *pathname)
  804. {
  805.     static char fixpath[ 512 ];
  806.     char*       pc = fixpath;
  807.  
  808.     while (*pathname) {
  809.         /* take care not to double escape things: i don't know
  810.         if this can happen so i'm gonna be paranoid <jae> */
  811.         if (pathname[0] == '\\' && pathname[1] == '\\') {
  812.             pc[0] = pc[1] = '\\';
  813.             pc += 2; pathname += 2;
  814.         } else if (pathname[0] == '\\')
  815.             *pc++ = '\\';
  816.         *pc++ = *pathname++;
  817.     }
  818.     *pc = 0;
  819.     return fixpath;
  820. }
  821.  
  822. #endif